package dexter.net.unit;

import static org.junit.Assert.assertTrue;

import java.io.IOException;

import org.junit.Before;
import org.junit.Test;

import dexter.net.Consumer;
import dexter.net.Producer;
import dexter.net.msg.common.ResponseListener;
import dexter.net.msg.common.RequestListener;
import dexter.net.msg.common.RequestParams;
import dexter.net.msg.common.ResponseParams;


public class NetTest {
	
	private Consumer consumer;
	private Producer producer;
	
	@Before
	public void init() {
		consumer = new Consumer(5555);
	    producer = new Producer("localhost", 5555);
	}

	@Test
	public void testProducerConsumer(){
		
		try {
		  
		  RequestListener tlistener = new NetTestListener();
		  consumer.receive(tlistener);
		  
		  ResponseListener rlistener = new NetResultListener();
		
		  //positive test
		  RequestParams params = new NetParams(1);  
		  producer.send(params, rlistener);		  
		  
		  //negative test
		  params = new NetParams(-1);
		  producer.send(params, rlistener);	
		  
		} catch(IOException e) {
			e.printStackTrace();
			assertTrue(false);
		}
		
		assertTrue(true);
	}
	
	
	public class NetTestListener implements RequestListener {

		public ResponseParams service(RequestParams params) {
			NetParams netParams = (NetParams) params;
		    int value = netParams.getValue();
		    
		    System.out.println("CONSUMER> IS POSITIVE? : "+value);
			if (value<0) return new NetResult(false, "negative");
			else return new NetResult(true, "positive");
		}

	}
	
	public class NetResultListener implements ResponseListener {

		public void errorArrive(ResponseParams result) {
			NetResult netResult = (NetResult) result;
			System.out.println("PRODUCER> ERROR : "+netResult);

		}

		public void resultArrive(ResponseParams result) {
			NetResult netResult = (NetResult) result;
			System.out.println("PRODUCER> RESULT : "+netResult);
		}

	}

}
